<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="500px" :title="`${drawerProps.title}客户`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="客户名称" prop="organizationName">
        <el-input v-model="drawerProps.row!.organizationName" placeholder="请输入客户名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="客户类型" prop="organizationType">
        <el-select filterable v-model="drawerProps.row!.organizationType" placeholder="请选择客户类型" clearable>
          <el-option v-for="item in customerTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input v-model="drawerProps.row!.contactName" placeholder="请输入联系人姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="账号" prop="contactAccount">
        <el-input v-model="drawerProps.row!.contactAccount" placeholder="请输入账号" clearable></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="contactPhone">
        <el-input v-model="drawerProps.row!.contactPhone" placeholder="请输入手机号" clearable></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="contactEmail">
        <el-input v-model="drawerProps.row!.contactEmail" placeholder="请输入邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item label="国家/地区">
        <el-select filterable v-model="drawerProps.row!.region" placeholder="请选择国家/地区" clearable>
          <el-option
            v-for="item in countryData || []"
            :key="item.id"
            :label="`${item.dialect}(${item.countryName})`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="省/市/区">
        <el-cascader
          ref="cascader"
          v-model="drawerProps.row!.citys"
          placeholder="请选择省/市/区"
          clearable
          filterable
          :props="cascaderProps"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" v-model="drawerProps.row!.remark" placeholder="请输入备注" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { customerTypes } from '../constant'
import { DrawerProps } from '../types'
import { FormInstance } from 'element-plus'
import { getCountryData, getAreas } from '../apis'

const rules = {
  organizationName: [{ required: true, message: '请输入客户名称' }],
  organizationType: [{ required: true, message: '请输入客户类型' }],
  contactName: [{ required: true, message: '请输入联系人姓名' }],
  contactAccount: [{ required: true, message: '请输入账号' }],
  contactPhone: [
    { required: true, message: '请输入手机号' },
    { required: true, pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入邮箱' },
    {
      required: true,
      pattern: /^[a-zA-Z0-9_-|.]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
      message: '邮箱格式不正确',
      trigger: 'blur'
    }
  ]
}

const drawerVisible = ref(false)
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: '',
  row: {}
})

// 获取国家/区域列表
const countryData = ref()
const initGetCountryData = () => {
  getCountryData({}).then((res) => {
    countryData.value = res
  })
}

// 省市区组件动态加载省市区
const lazyLoad = (node, resolve) => {
  const { value, level } = node
  getAreas({ countryCode: 0, code: value || '' }).then((res) => {
    const nodes = res.map((item) => {
      return {
        ...item,
        leaf: level >= 2
      }
    })
    resolve(nodes)
  })
}

const cascaderProps = {
  lazy: true,
  label: 'name',
  value: 'code',
  lazyLoad
}

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params
  drawerVisible.value = true
  initGetCountryData()
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>()
// const cascader = ref()
const handleSubmit = () => {
  ruleFormRef.value!.validate(async (valid) => {
    if (!valid) return
    try {
      const item: any = drawerProps.value.row
      // 获取省市区名称
      // if (item[0] && item[1] && item[2]) {
      //   const checkedNodes = cascader.value.getCheckedNodes()
      //   const pathLabels = checkedNodes[0].pathLabels
      //   console.warn('pathLabels', pathLabels)
      // }
      const params: any = {
        organizationName: item.organizationName,
        contactAccount: item.contactAccount,
        contactEmail: item.contactEmail,
        contactName: item.contactName,
        contactPhone: item.contactPhone,
        remark: item.remark,
        organizationType: item.organizationType,
        region: item.region,
        provinceCode: item.citys[0] || '',
        cityCode: item.citys[1] || '',
        areaCode: item.citys[2] || ''
      }
      if (item.customerId) {
        params.customerId = item.customerId
      }
      await drawerProps.value.api!(params)
      ElMessage.success({ message: `${drawerProps.value.title}客户成功！` })
      drawerProps.value.getTableList!()
      drawerVisible.value = false
    } catch (error) {
      console.log(error)
    }
  })
}

defineExpose({
  acceptParams
})
</script>
